package com.kuaixueit.crm.controller;

import java.util.HashMap;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.github.pagehelper.PageInfo;
import com.kuaixueit.crm.pojo.CDept;
import com.kuaixueit.crm.pojo.ResultVO;
import com.kuaixueit.crm.service.DeptService;

@Controller //实例化deptController放到spring容器
@RequestMapping("dept") //窄化路径
public class DeptController {
	
	@Autowired
	private DeptService deptService;
	
	/**
	 * 
	 * @param deptName部门名称
	 * @param page 页码 默认值为1
	 * @param rows 每页大小默认值为3
	 * @return
	 */
	@RequestMapping("list")
	@ResponseBody //返回值hashmap对象转化为json数据
	public Map getListByDeptName(String deptName,
			//@RequestParam(defaultValue="1")如果不传递参数默认是1
			@RequestParam(defaultValue="1")Integer page,
			@RequestParam(defaultValue="3")Integer rows){
		Map map = new HashMap();
		try {
			//分页查询
			PageInfo info = deptService.findPage(deptName, page, rows);
			//符合条件的总数
			map.put("total", info.getTotal());
			//当前页的数据
			map.put("rows", info.getList());
		} catch (Exception e) {
			e.printStackTrace();
		}
		return map;
	}
	
	/**
	 * 批量删除部门
	 * @param ids
	 * @return
	 */
	@RequestMapping("delete")
	@ResponseBody
	public ResultVO deleteByIds(Integer[] ids){
		try {
			deptService.deleteByIds(ids);
			return new ResultVO(0, null, "删除成功");
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		return new ResultVO("删除失败请重试");
	}
	
	
	/**
	 * 增加一个部门
	 * @param dept
	 * @return
	 */
	@RequestMapping("add")
	@ResponseBody
	public ResultVO add(CDept dept){
		dept.setId(null);
		try {
			deptService.saveDept(dept);
			return new ResultVO(0, null, "新增成功");
		} catch (Exception e) {
			e.printStackTrace();
		}
		return new ResultVO("新增失败请重试");
		
	}
	
	/**
	 * 修改部门 必须带id
	 * @param dept
	 * @return
	 */
	@RequestMapping("update")
	@ResponseBody
	public ResultVO update(CDept dept){
		return deptService.update(dept);
	}

}
